// window.onload = function () {
    console.log("DeepLTranslatorHelper.js loaded");

    //  ======================= 地址栏携带id和type参数
    function getHashParams() {
        const hash = window.location.hash.substring(1); // 去掉开头的#
        const params = new URLSearchParams(hash);
        return {
            cid: params.get("id") || "",
            ctype: params.get("type") || "",
        };
    }
    // 使用示例
    //   const { id, type } = getHashParams();
    //   console.log("ID:", id, "Type:", type);

    // ======================= 标签页标题
    function getLanguageCodes() {
        try {
            const url = window.location.href;
            // 匹配任意语言代码对的正则表达式
            const langPattern = /#([a-z]{2}(?:-[a-z]{2,4})?)\/([a-z]{2}(?:-[a-z]{2,4})?)\//;

            const match = url.match(langPattern);

            if (match && match.length > 2) {
                return {
                    sourceLang: match[1],
                    targetLang: match[2]
                };
            }
            return null;
        } catch (error) {
            console.error("Error extracting language codes:", error);
            return null;
        }
    }
    let languageCodes = getLanguageCodes();
    console.log("languageCodes", languageCodes);

    const languageMap = {
        en: "英语",
        fr: "法语",
        de: "德语",
        it: "意大利",
        es: "西班牙",
        "zh-hans": "中文简体",
        nl: "荷兰",
        sv: "瑞典",
        pl: "波兰",
    };
    document.querySelector("head > title").textContent = getLanguageCodes().targetLang;
    // 存储当前的targetLang值
    let currentTlValue = getLanguageCodes().targetLang;

    // 定义一个函数来检查targetLang参数的变化
    function checkTlChange() {
        const newTlValue = getLanguageCodes().targetLang;
        if (newTlValue !== currentTlValue || document.querySelector("head > title").textContent !== languageMap[newTlValue]) {
            console.log(`tl 参数已更改：从 ${currentTlValue} 到 ${newTlValue}`);
            document.querySelector("head > title").textContent =languageMap[newTlValue];
            currentTlValue = newTlValue; // 更新当前值以便下次比较
        }
    }

    // 初始化检查（以防页面加载时已经有tl参数）
    checkTlChange();

    // 设置一个观察者来监听URL的变化（注意：这种方法可能无法直接捕获所有URL变化，特别是由JavaScript动态更改的）
    // 由于Google Translate页面可能不会通过传统的history API更改URL（例如，使用pushState），我们需要一个不同的策略
    // 在这个场景中，我们可以使用MutationObserver来观察location对象的属性变化，但location对象的变化通常会导致页面重新加载
    // 因此，更实用的方法是轮询或使用其他事件监听机制（如果可用）
    // 然而，为了简化示例，我们将使用轮询
    setInterval(checkTlChange, 1000); // 每秒检查一次

    // 注意：轮询可能不是最高效的方法，但它在这个简单的示例中是可行的
    // 在生产环境中，你可能需要寻找更优雅的解决方案来监听URL变化










    // ======================= 切换语言按钮
    let switchLanguage = document.createElement("div");
    switchLanguage.style.position = "fixed";
    switchLanguage.style.top = "0px";
    switchLanguage.style.left = "50%";
    switchLanguage.style.width = "530px";
    switchLanguage.style.backgroundColor = "#f9f9f9";
    // switchLanguage.style.padding = "5px";
    switchLanguage.style.paddingTop = "10px";
    switchLanguage.style.paddingBottom = "10px";
    switchLanguage.style.border = "1px solid #ddd";
    switchLanguage.style.borderRadius = "8px";
    switchLanguage.style.zIndex = "10000";
    const languages = [
        "中文",
        "英语",
        "法语",
        "德语",
        "意大利",
        "西班牙",
        "荷兰",
        "瑞典",
        "波兰",
    ];
    const countries = ["zh-hans", "en", "fr", "de", "it", "es", "nl", "sv", "pl"];
    for (let i = 0; i < languages.length; i++) {
        let button = document.createElement("button");
        button.textContent = languages[i];
        button.addEventListener("click", () => {
            let url0 = window.location.href;
            let tl = getLanguageCodes().targetLang;
            console.log('%c [ tl ]-119', 'font-size:13px; background:pink; color:#bf2c9f;', tl)
            const langPattern = /(#([a-z]{2}(?:-[a-z]{2,4})?)\/)([a-z]{2}(?:-[a-z]{2,4})?)(\/)/;
            let url1 = url0.replace(langPattern, `$1${countries[i]}$4`);
            console.log('%c [ url ]-120', 'font-size:13px; background:pink; color:#bf2c9f;', url1)
            if (url0 === url1) {
                alert("当前语言已是" + languages[i]);
                return;
            }
            window.open(url1, "_self");
            // document.getElementById("headlessui-popover-button-:re:").click();
            // ddocument.querySelector('[data-testid="translator-lang-option-'+countries[i]+'"]').click();
        });
        button.style.marginLeft = "6px";
        button.style.marginRight = "5px";
        button.style.height = "40px";
        button.style.border = "1px solid #ddd";
        button.style.borderRadius = "8px";
        button.style.padding = "5px";
        switchLanguage.appendChild(button);
    }
    document.body.appendChild(switchLanguage);









    // ======================= 复制按钮
    let CopyContainer = document.createElement("div");
    CopyContainer.style.position = "fixed";
    CopyContainer.style.top = "0px";
    CopyContainer.style.left = "35.4%";
    CopyContainer.style.width = "210px";
    CopyContainer.style.backgroundColor = "#f9f9f9";
    CopyContainer.style.padding = "10px";
    CopyContainer.style.border = "1px solid #ddd";
    CopyContainer.style.borderRadius = "8px";
    CopyContainer.style.zIndex = "10000";

    let bt_CopyOriginal = document.createElement("button");
    bt_CopyOriginal.textContent = "复制原文";
    bt_CopyOriginal.style.height = "40px";
    bt_CopyOriginal.style.border = "1px solid #ddd";
    bt_CopyOriginal.style.marginLeft = "10px";
    // bt_CopyOriginal.style.marginRight = "10px";
    bt_CopyOriginal.style.padding = "5px";
    bt_CopyOriginal.style.borderRadius = "8px";
    bt_CopyOriginal.addEventListener("click", function () {
        let txt = document.querySelector("#textareasContainer > div.rounded-es-inherit.relative.min-h-\\[240px\\].min-w-0.md\\:min-h-\\[clamp\\(250px\\,50vh\\,557px\\)\\].h-full.mobile\\:min-h-0.mobile\\:h-auto.TextTranslatorLayout-module--textareaContainerMobilePortraitMaxHeight--50d46 > section > div > div.relative.flex-1.rounded-inherit.mobile\\:min-h-0 > d-textarea > div:nth-child(1) > p > span").textContent;
        const textarea = document.createElement("textarea");
        textarea.value = txt;
        textarea.style.position = "absolute";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("CopyContainer");
        document.body.removeChild(textarea);
    });
    CopyContainer.appendChild(bt_CopyOriginal);

    let bt_CopyTranslation = document.createElement("button");
    bt_CopyTranslation.textContent = "复制译文";
    bt_CopyTranslation.style.height = "40px";
    bt_CopyTranslation.style.border = "1px solid #ddd";
    bt_CopyTranslation.style.marginLeft = "10px";
    // bt_CopyTranslation.style.marginRight = "10px";
    bt_CopyTranslation.style.padding = "5px";
    bt_CopyTranslation.style.borderRadius = "8px";
    bt_CopyTranslation.addEventListener("click", function () {
        document.querySelector('[data-testid="translator-target-toolbar-copy"]').click();
    });
    CopyContainer.appendChild(bt_CopyTranslation);

    document.body.appendChild(CopyContainer);





